<template>
	<view class="withdraw-container">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 顶部按钮 -->
		<view class="top-btn" @tap="goToWithdrawAccount">
			<text class="iconfont icon-wallet"></text>
			<text class="btn-text">提现账户</text>
		</view>

		<!-- 提现金额输入 -->
		<view class="amount-card">
			<view class="card-title">提现金额</view>
			<view class="amount-input" @tap="focusAmountInput">
				<text class="currency">¥</text>
				<input class="amount" type="text" v-model="amount" placeholder="0.00" :focus="amountFocus"
					@focus="onAmountFocus" @blur="onAmountBlur" @input="onAmountInput" ref="amountInput" />
			</view>
			<view class="available-amount">
				总可提现金额{{ availableAmount }}元
				<text class="withdraw-all" @tap="withdrawAll">全部提现</text>
			</view>
		</view>

		<!-- 提现方式选择 -->
		<view class="withdraw-methods">
			<!-- 支付宝提现 -->
			<view class="method-item" @tap="selectMethod('alipay')">
				<view class="method-left">
					<image src="/static/icon/alipay.png" class="method-icon" mode="aspectFit"></image>
					<text class="method-name">提现至支付宝</text>
				</view>
				<view class="method-right">
					<text class="method-status" v-if="!alipayAccount">请先设置提现账户</text>
					<text class="method-account" v-else>{{ alipayAccount }}</text>
					<radio :checked="selectedMethod === 'alipay'" color="#2B85E4" />
				</view>
			</view>

			<!-- 银行卡提现 -->
			<view class="method-item" @tap="selectMethod('bank')">
				<view class="method-left">
					<image src="/static/icon/bank-card.png" class="method-icon" mode="aspectFit"></image>
					<text class="method-name">提现至银行卡</text>
				</view>
				<view class="method-right">
					<text class="method-status" v-if="!bankAccount">请先设置提现账户</text>
					<text class="method-account" v-else>{{ bankAccount }}</text>
					<radio :checked="selectedMethod === 'bank'" color="#2B85E4" />
				</view>
			</view>
		</view>

		<!-- 提现说明 -->
		<view class="withdraw-notice">
			<view class="notice-title">提现说明</view>
			<view class="notice-item">1. 提现金额最低1元起；</view>
			<view class="notice-item">2. 提现申请提交后，预计1-3个工作日到账；</view>
			<view class="notice-item">3. 如遇节假日，到账时间可能会有延迟；</view>
			<view class="notice-item">4. 如有疑问，请联系客服。</view>
		</view>

		<!-- 提现按钮 -->
		<button class="withdraw-btn" :disabled="!canWithdraw" @tap="submitWithdraw">
			确认提现
		</button>
	</view>
</template>

<script>
	import TechNavBar from '@/components/tech-nav-bar.vue'
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			TechNavBar,
			NavBar
		},

		data() {
			return {
				amount: '', // 提现金额
				availableAmount: '0.00', // 可提现金额
				selectedMethod: 'alipay', // 默认选择支付宝提现
				alipayAccount: '', // 支付宝账号
				bankAccount: '', // 银行卡账号
				alipayAccountId: '', // 支付宝账户ID
				bankAccountId: '', // 银行卡账户ID
				amountFocus: false, // 控制金额输入框焦点
				accountList: [], // 账户列表
				type: 'order', // 默认订单钱包提现
				isSubmitting: false, // 是否正在提交
				withdrawConfig: {
					minAmount: 1, // 最小提现金额
					maxAmount: 50000 // 最大提现金额
				},
				techId: ''
			}
		},

		computed: {
			// 判断是否可以提现
			canWithdraw() {
				// 金额必须大于0且不超过可提现金额
				const amountNum = parseFloat(this.amount) || 0;
				const availableNum = parseFloat(this.availableAmount) || 0;

				// 金额有效且有对应的提现账户
				const hasAccount = (this.selectedMethod === 'alipay' && this.alipayAccount) ||
					(this.selectedMethod === 'bank' && this.bankAccount);

				return amountNum >= 1 && amountNum <= availableNum && hasAccount;
			}
		},

		onLoad(options) {
			if (options.type) {
				this.type = options.type
			}
			if (options.amount) {
				this.availableAmount = options.amount;
			}
			if (options.accountId) {
				const accountType = options.accountType || 'alipay';
				if (accountType === 'alipay') {
					this.alipayAccountId = options.accountId;
				} else {
					this.bankAccountId = options.accountId;
				}
			}
			this.loadAccountInfo();
		},

		onShow() {
			this.loadAvailableAmount();
			this.loadAccountInfo();
		},

		methods: {
			// 加载账户信息
			async loadAccountInfo() {
				uni.showLoading({
					title: '加载中...'
				});

				try {
					// 从本地存储获取技师ID
					const userInfo = uni.getStorageSync('userInfo');
					const techId = userInfo ? userInfo.techId : null;

					if (!techId) {
						uni.showToast({
							title: '未获取到技师信息，请重新登录',
							icon: 'none'
						});
						return;
					}

					// 构建请求参数
					const params = {
						technicianId: techId
					};

					// 调用后端API获取账户列表
					const result = await uni.request({
						url: `${uni.$config.baseUrl}/tehcAccount/tehcAccount/listAll`,
						method: 'GET',
						data: params,
						header: {
							'Authorization': uni.getStorageSync('token')
						}
					});

					if (result.data.code === 200) {
						// 获取账户列表
						this.accountList = result.data.rows || [];

						// 处理支付宝和银行卡账户信息
						this.processAccountList();
					} else {
						throw new Error(result.data.msg || '获取账户信息失败');
					}
				} catch (err) {
					console.error('获取账户信息失败:', err);
					uni.showToast({
						title: '获取账户信息失败',
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 处理账户列表
			processAccountList() {
				// 遍历账户列表
				this.accountList.forEach(account => {
					// 支付宝账户 (accountType = 1)
					if (account.accountType === 1 && account.account) {
						this.alipayAccount = this.formatAccount(account.account, 'alipay');
						this.alipayAccountId = account.id;
					}
					// 银行卡账户 (accountType = 2)
					else if (account.accountType === 2 && account.cardNumber) {
						const bankInfo = account.bankName ? `${account.bankName} ` : '';
						this.bankAccount = bankInfo + this.formatAccount(account.cardNumber, 'bank');
						this.bankAccountId = account.id;
					}
				});

				// 如果没有默认选中的账户类型的账户，但有另一种类型的账户，则切换选中类型
				if (this.selectedMethod === 'alipay' && !this.alipayAccount && this.bankAccount) {
					this.selectedMethod = 'bank';
				} else if (this.selectedMethod === 'bank' && !this.bankAccount && this.alipayAccount) {
					this.selectedMethod = 'alipay';
				}
			},

			// 格式化账户显示
			formatAccount(account, type) {
				if (!account) return '';

				if (type === 'alipay') {
					// 支付宝账号：保留前3位和后4位，中间用****代替
					if (account.includes('@')) {
						// 邮箱格式
						const parts = account.split('@');
						const username = parts[0];
						const domain = parts[1];
						if (username.length > 3) {
							return username.substring(0, 3) + '****@' + domain;
						}
						return account;
					} else {
						// 手机号格式
						return account.replace(/(\d{3})\d*(\d{4})/, '$1****$2');
					}
				} else if (type === 'bank') {
					// 银行卡：仅显示后4位
					return `(${account.slice(-4)})`;
				}
				return account;
			},

			// 选择提现方式
			selectMethod(method) {
				// 如果没有对应的账户，跳转到设置账户页面
				if ((method === 'alipay' && !this.alipayAccount) || (method === 'bank' && !this.bankAccount)) {
					uni.navigateTo({
						url: `/pages/technician/set-account?type=${method}`
					});
					return;
				}

				this.selectedMethod = method;
			},

			// 聚焦金额输入框
			focusAmountInput() {
				this.amountFocus = true;
			},

			// 金额输入框获得焦点
			onAmountFocus() {
				this.amountFocus = true;
			},

			// 金额输入事件（实时限制格式，超额校验放到 blur）
			onAmountInput(e) {
				const value = e.detail.value;

				// 只允许数字和两位小数
				if (value && !/^\d*(?:\.\d{0,2})?$/.test(value)) {
					this.amount = this.amount; // 恢复上一次合法值
					return;
				}
				// 暂存最新值，不做超额判断，减少输入干扰
				this.amount = value;
			},

			// 金额输入框失去焦点
			onAmountBlur() {
				this.amountFocus = false;

				// 格式化金额并做最终合法性校验
				if (this.amount) {
					let amountNum = parseFloat(this.amount);
					if (isNaN(amountNum)) {
						amountNum = 0;
					}

					const availableNum = parseFloat(this.availableAmount) || 0;
					if (amountNum > availableNum) {
						amountNum = availableNum;
						uni.showToast({ title: '提现金额不能超过可提现金额', icon: 'none' });
					} else if (amountNum > 0 && amountNum < this.withdrawConfig.minAmount) {
						// 小于最小提现金额提示
						uni.showToast({ title: `最低提现金额为${this.withdrawConfig.minAmount}元`, icon: 'none' });
					}

					this.amount = amountNum.toFixed(2);
				}
			},

			// 全部提现
			withdrawAll() {
				this.amount = this.availableAmount;
			},

			// 提交提现申请
			async submitWithdraw() {
				// 防止重复提交
				if (this.isSubmitting) {
					return
				}

				if (!this.canWithdraw) {
					return
				}

				// 获取技师ID
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || !userInfo.techId) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}
				this.techId = userInfo.techId

				// 确认提现
				const confirmRes = await new Promise((resolve) => {
					uni.showModal({
						title: '确认提现',
						content: `确认提现${this.amount}元到${this.selectedMethod === 'alipay' ? '支付宝' : '银行卡'}账户？`,
						success: (res) => {
							resolve(res.confirm)
						}
					})
				})

				if (!confirmRes) return

				try {
					this.isSubmitting = true
					uni.showLoading({
						title: '提交中...'
					})

					// 获取选中的账户信息
					const selectedAccount = this.selectedMethod === 'alipay' ? {
						id: this.alipayAccountId,
						type: 1
					} : {
						id: this.bankAccountId,
						type: 2
					}

					if (!selectedAccount.id) {
						throw new Error('请先设置提现账户')
					}

					// 检查所有必要参数
					const withdrawAmount = parseFloat(this.amount)
					if (!withdrawAmount || withdrawAmount <= 0) {
						throw new Error('请输入正确的提现金额')
					}

					// 最小提现金额校验
					if (withdrawAmount < this.withdrawConfig.minAmount) {
						uni.showModal({
							title: '提示',
							content: `最低提现金额为${this.withdrawConfig.minAmount}元`,
							showCancel: false
						})
						return
					}

					const token = uni.getStorageSync('token')
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: `${uni.$config.baseUrl}/tehcAccount/tehcAccount/withdraw/apply`,
							method: 'POST',
							header: {
								'Authorization': 'Bearer ' + token,
								'Content-Type': 'application/json'
							},
							data: {
								technicianId: this.techId,
								amount: withdrawAmount,
								accountId: selectedAccount.id,
								accountType: selectedAccount.type,
								withdrawNo: '', // 后端会生成
								accountName: '', // 后端会从账户信息获取
								accountNo: '', // 后端会从账户信息获取
								bankName: '', // 后端会从账户信息获取
								status: 0 // 初始状态：处理中
							},
							success: (response) => {
								resolve(response)
							},
							fail: (error) => {
								reject(error)
							}
						})
					})

					const result = res.data

					if (result.code === 200) {
						// 提现成功
						uni.showToast({
							title: '提现申请已提交，预计1-3个工作日到账',
							icon: 'success',
							duration: 2000
						})

						// 提现成功后返回上一页
						setTimeout(() => {
							// 返回上一页并刷新
							const pages = getCurrentPages()
							const prevPage = pages[pages.length - 2]
							if (prevPage && prevPage.$vm && prevPage.$vm.loadWalletInfo) {
								prevPage.$vm.loadWalletInfo()
							}
							uni.navigateBack()
						}, 2000)
					} else {
						// 提现失败
						const errorMsg = result.msg || '提现申请失败'
						uni.showModal({
							title: '提现失败',
							content: errorMsg,
							showCancel: false
						})
					}
				} catch (err) {
					console.error('提现申请失败:', err)
					uni.showModal({
						title: '提现失败',
						content: err.message || '提现申请失败',
						showCancel: false
					})
				} finally {
					uni.hideLoading()
					// 延迟重置提交状态，防止快速点击
					setTimeout(() => {
						this.isSubmitting = false
					}, 2000)
				}
			},

			goBack() {
				uni.navigateBack()
			},

			goToWithdrawAccount(type) {
				uni.navigateTo({
					url: `/pages/technician/withdraw-account?type=${type}`
				})
			},

			// 加载可提现金额
			async loadAvailableAmount() {
				try {
					// 从本地存储获取技师ID和token
					const userInfo = uni.getStorageSync('userInfo');
					const token = uni.getStorageSync('token');
					const techId = userInfo ? userInfo.techId : null;

					if (!techId || !token) {
						uni.showToast({
							title: '登录信息已失效，请重新登录',
							icon: 'none'
						});
						return;
					}

					// 构建请求参数
					const params = {
						technicianId: techId
					};

					// 调用后端API获取钱包数据
					const result = await uni.request({
						url: `${uni.$config.baseUrl}/techWallet/techWallet/listAll`,
						method: 'GET',
						data: params,
						header: {
							'Content-Type': 'application/json',
							'Authorization': 'Bearer ' + token
						}
					});

					if (result.data.code === 200) {
						// 获取钱包列表
						const walletList = result.data.rows || [];

						// 获取钱包数据
						if (walletList.length > 0) {
							const walletData = walletList[0];
							// 更新可提现金额，保留两位小数
							this.availableAmount = this.formatAmount(walletData.balance);
						}
					} else {
						throw new Error(result.data.msg || '获取钱包信息失败');
					}
				} catch (err) {
					console.error('获取钱包信息失败:', err);
					uni.showToast({
						title: '获取钱包信息失败',
						icon: 'none'
					});

					// 如果是token相关错误，可以跳转到登录页面
					if (err.message && err.message.includes('JWT')) {
						setTimeout(() => {
							uni.navigateTo({
								url: '/pages/login/login'
							});
						}, 1500);
					}
				}
			},

			// 格式化金额，保留两位小数
			formatAmount(amount) {
				return parseFloat(amount || 0).toFixed(2);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.withdraw-container {
		min-height: 100vh;
		background: #F5F5F5;
		padding-bottom: 120rpx;

		// 顶部按钮样式
		.top-btn {
			position: fixed;
			top: 40rpx;
			right: 30rpx;
			display: flex;
			align-items: center;
			padding: 12rpx 24rpx;
			background: #2B85E4;
			border-radius: 30rpx;
			z-index: 100;

			.iconfont {
				font-size: 32rpx;
				color: #FFFFFF;
				margin-right: 8rpx;
			}

			.btn-text {
				font-size: 28rpx;
				color: #FFFFFF;
			}
		}

		.amount-card {
			background: #FFFFFF;
			padding: 40rpx 30rpx;
			margin-bottom: 20rpx;

			.card-title {
				font-size: 28rpx;
				color: #666666;
				margin-bottom: 30rpx;
			}

			.amount-input {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;

				.currency {
					font-size: 48rpx;
					font-weight: bold;
					color: #333333;
					margin-right: 10rpx;
				}

				.amount {
					flex: 1;
					font-size: 60rpx;
					font-weight: bold;
					color: #333333;
					height: 80rpx;
					line-height: 80rpx;
				}
			}

			.available-amount {
				font-size: 24rpx;
				color: #999999;

				.withdraw-all {
					color: #2B85E4;
					margin-left: 20rpx;
				}
			}
		}

		.withdraw-methods {
			background: #FFFFFF;
			margin-bottom: 20rpx;

			.method-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #F5F5F5;

				&:last-child {
					border-bottom: none;
				}

				.method-left {
					display: flex;
					align-items: center;

					.method-icon {
						width: 48rpx;
						height: 48rpx;
						margin-right: 20rpx;
						filter: brightness(0) saturate(100%) invert(45%) sepia(45%) saturate(2120%) hue-rotate(194deg) brightness(96%) contrast(88%);
					}

					.method-name {
						font-size: 32rpx;
						color: #333333;
					}
				}

				.method-right {
					display: flex;
					align-items: center;

					.method-status {
						font-size: 28rpx;
						color: #999999;
						margin-right: 20rpx;
					}

					.method-account {
						font-size: 28rpx;
						color: #666666;
						margin-right: 20rpx;
					}
				}
			}
		}

		.withdraw-notice {
			background: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 40rpx;

			.notice-title {
				font-size: 28rpx;
				color: #333333;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.notice-item {
				font-size: 24rpx;
				color: #999999;
				line-height: 1.6;
			}
		}

		.withdraw-btn {
			position: fixed;
			left: 30rpx;
			right: 30rpx;
			bottom: 40rpx;
			height: 88rpx;
			line-height: 88rpx;
			background: #2B85E4;
			color: #FFFFFF;
			font-size: 32rpx;
			border-radius: 44rpx;
			text-align: center;

			/* 禁用状态：按钮置灰 */
			&:disabled {
				background: #c0c4cc; /* 灰色 */
				color: #ffffff;
				opacity: 1;          /* 覆盖默认透明度，直接用置灰颜色 */
			}

			&::after {
				border: none;
			}
		}
	}
</style>